import { $modal } from '@/plugins'

export class GEOObj {
  longitude: number
  latitude: number
}
export enum PositioningModel {
  STATIC = 0, // 静态的（手动刷新GEO）
  LASTING = 1 // 持久的（自动刷新GEO）
}
export default class GEO {
  public value = new GEOObj()
  public timer: number | null
  public interval: number
  private onRefreshListener: ((gel: GEOObj) => void)[] = []
  constructor(model: number, interval: number = 1000 * 60) {
    this.interval = interval
    this.setModel(model)
  }
  public refresh(): Promise<GEOObj | null> {
    console.log('准备请求位置')
    return new Promise((resolve, reject) => {
      const that = this
      uni.authorize({
        scope: 'scope.userLocation',
        success: (success) => {
          uni.getLocation({
            isHighAccuracy: true,
            type: 'gcj02', // 默认为 wgs84,改为gcj02，因为map标签在微信小程序上使用腾讯地图，腾讯地图使用gcj02
            success: async function (res) {
              that.value.longitude = res.longitude
              that.value.latitude = res.latitude
              resolve(that.value)
            },
            fail(err) {
              $modal.toastErrorMsg('无法获取位置信息，请检查是否开启定位,否则将无法正常使用！')
              resolve(null)
            }
          })
        },
        fail(err) {
          resolve(null)
        }
      })
    })
  }
  public async refreshAndGet() {
    await this.refresh()
    if (isNaN(this.value.longitude) || isNaN(this.value.latitude)) {
      throw new Error('无法获取位置信息！')
    }
    return this.value
  }
  public async setModel(model: number) {
    if (this.timer != null) {
      clearInterval(this.timer)
      this.timer = null
    }
    if (model === PositioningModel.STATIC) {
      await this.refresh()
    } else {
      this.timer = setInterval(async () => {
        await this.refresh()
        // 通知监听者
        this.onRefreshListener.forEach((listener) => listener(this.value))
      }, this.interval)
    }
  }
  public addOnRefreshListener(listener: (position: GEOObj) => void) {
    this.onRefreshListener.push(listener)
    // 返回移除函数
    return () => {
      this.onRefreshListener = this.onRefreshListener.filter((item) => item !== listener)
    }
  }
}
